<?php

/**
 * 产品基本信息仓库
 * @author wangwx 2015-5-12
 */
namespace common\repositories\myhtsq;
use common\repositories\BaseRepository;
use common\support\StringHelper;
use common\entities\myhtsq\ApplicationInfoEntity;
use common\entities\myhtsq\ApplicationPriceEntity;
use Yii;

class ApplicationInfoRepository extends BaseRepository{

	/**
	 * 构造方法
	 * @param unknown $config (optional)
	 */
	public function __construct($config = [])
	{
		parent::__construct($config);
	}


	/**
	 * 根据关键字，获取产品名称列表
	 * @param string $keyword 关键字
	 * @param int $limit 返回条数，传空：全部返回
	 * @return array
	 */
	public static function getApplicationInfoByKeyword($keyword,$limit='',$other=0) {

		$query = ApplicationInfoEntity::find();

        $query->where(['is_off_shelf'=>0]);

        //sonar 坏味道修复

        if(!empty($keyword)){
            $query->andFilterWhere([
                'and' ,
                ['like', 'application_name', $keyword],
                ['=', 'is_off_shelf', 0],
                
            ]);
           //sonar 坏味道修复
        }

		//其他产品
		if ($other != 0) {
			$query->andFilterWhere(["in_other" => 1]);
		}else{
			$query->andFilterWhere(["in_other" => 0]);
		}

		if (intval($limit)>0) {
			$query->limit($limit);
		}
		return $query->orderBy('created_on ASC')->all();
	}

	/**
	 * 根据产品ID获取单个产品
	 * @param $id
	 * @return array|null|\yii\db\ActiveRecord
	 */
	public static function getApplicationInfoById($id)
	{
		$sql = "select * from myscrm_application_info as t1 left join myscrm_application_price as t2 on t1.application_id=t2.application_id where t1.application_id=:application_id";
		return ApplicationInfoEntity::getDb()->createCommand($sql)->bindValues([":application_id" => $id])->queryOne();
	}

    /**
     * 根据产品ID获取产品信息
     * @param $id
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function getApplicationInfoByApplicationId($application_id)
    {
        //sonar 坏味道修复
        return ApplicationInfoEntity::find()->where(['application_id'=>$application_id])->asArray()->one();
    }

    /**
     * 根据产品ID获取产品信息
     * @param $id
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function getApplicationInfoByAuthorizeUniqueName($authorize_unique_name,$IsQdAdvanced=0)
    {
        //sonar 坏味道修复
        return ApplicationInfoEntity::find()->where(['authorize_unique_name'=>$authorize_unique_name])->andWhere(['IsQdAdvanced'=>$IsQdAdvanced])->asArray()->one();
    }


    /**
     * 根据产品ID获取产品名称
     *
     * @param $applicationId
     * @return bool|string
     */
    public static function getApplicationNameByApplicationId($applicationId)
    {
        //sonar 坏味道修复
        return ApplicationInfoEntity::find()->select('application_name')->where(['application_id'=>$applicationId])->scalar();
    }

    /**
     * 根据多个产品ID获取产品信息
     *
     * @author    chenjy01
     * @version   1.0
     * @link      http://www.myunke.com/
     * @param    $ids         array 多个产品ID
     * @return   array|null
     */
    public static function getApplicationInfoByApplicationIds($ids)
    {
        $field = 'infoObj.application_id,infoObj.application_name,infoObj.is_saas,infoObj.is_off_shelf,priceObj.price,priceObj.unit,';
        $field.= 'infoObj.buss_type_id';

        $map['infoObj.application_id'] = $ids;

        $query = ApplicationInfoEntity::find()->select($field)
                                              ->where($map)
                                              ->from(ApplicationInfoEntity::tableName() . ' AS infoObj')
                                              ->join('INNER JOIN',ApplicationPriceEntity::tableName() . ' AS priceObj', 'infoObj.application_id = priceObj.application_id');

        $result = $query->asArray()->all();

        return $result;
    }

    /**
     * 根据产品名称获取产品信息
     *
     * @param $name string 产品名称
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function getApplicationInfoByName($name)
    {
        $map['application_name'] = $name;

        $field = 'appObject.application_id,appObject.application_name,appObject.authorization_type,appObject.show_name,appObject.is_other,';
        $field.= 'appObject.in_other,appObject.is_simple,appObject.is_saas,appObject.delivery_rules,appObject.provisioning_type,appObject.matching_rule';

        $result = ApplicationInfoEntity::find()->from(ApplicationInfoEntity::tableName() . ' AS appObject')
                                               ->select($field)
                                               ->where($map)
                                               ->asArray()
                                               ->joinWith('price')
                                               ->one();

        return $result;
    }

    /**
     * 根据产品ID获取产品信息
     *
     * @param $id string 产品ID
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function getApplicationInfoByAppId($id)
    {
        $map['appObject.application_id'] = $id;

        $field = 'appObject.application_id,appObject.application_name,appObject.authorization_type,appObject.show_name,appObject.is_other,';
        $field.= 'appObject.in_other,appObject.is_simple,appObject.is_saas,appObject.delivery_rules,appObject.provisioning_type,appObject.matching_rule';

        $result = ApplicationInfoEntity::find()->from(ApplicationInfoEntity::tableName() . ' AS appObject')
                                               ->select($field)
                                               ->where($map)
                                               ->asArray()
                                               ->joinWith('price')
                                               ->one();

        return $result;
    }

    /**
     * 添加产品主数据
     *
     * @author    chenjy01
     * @version   1.0
     * @link      http://www.myunke.com/
     * @list      array  产品主数据数组 : list = ['appResult' => [], 'priceResult' => []]
     * @return    boolean
     */
    public static function addApplication($list)
    {
        $db = Yii::$app->contractDB;

        /* 注意这里为映射关系，如果新增字段，需要调整 */
        $appFields = [
            'application_id',
            'application_name',
            'is_off_shelf',
            'buss_type_id',
            'delivery_rules',
            'provisioning_type',
            'matching_rule',
            'created_on',
            'created_by',
        ];

        $priceFields = [
            'application_id',
            'price',
            'unit',
            'price_id',
            'created_on',
            'created_by',
        ];

        $transaction = $db->beginTransaction();

        try{
            if(! empty($list['appResult'])){
                $db->createCommand()->batchInsert(ApplicationInfoEntity::tableName(), $appFields, $list['appResult'])
                                    ->execute();
            }

            if(! empty($list['priceResult'])){
                $db->createCommand()->batchInsert(ApplicationPriceEntity::tableName(), $priceFields, $list['priceResult'])
                                    ->execute();
            }

            Yii::info('商机系统产品主数据同步成功，参数：' . json_encode($list));

            $result = true;
            $transaction->commit();
        } catch (\Exception $e){
            Yii::info('商机系统产品主数据同步失败，原因：' . $e->getMessage());

            $result = false;
            $transaction->rollBack();
        }

        return $result;
    }

    /**
     * 更新产品主数据
     *
     * @author    chenjy01
     * @version   1.0
     * @link      http://www.myunke.com/
     * @param     $appList   array 产品信息
     * @param     $priceList array 价格信息
     * @return    bool
     */
    public static function updateApplication($list){

        $db = Yii::$app->contractDB;
        $transaction = $db->beginTransaction();

        try{
            if(! empty($list['appResult'])){
                foreach ($list['appResult'] as $value){
                    $data = [
                        'application_name' => $value['application_name'],
                        'is_off_shelf'     => $value['is_off_shelf'],
                        'buss_type_id'     => $value['buss_type_id'],
                        'modified_on'      => $value['modified_on'],
                        'modified_by'      => $value['modified_by'],
                    ];

                    $map = [
                        'application_id' => $value['application_id'],
                    ];

                    Yii::info('商机系统产品主数据，信息更新参数：' . json_encode($data));

                    $db->createCommand()->update(ApplicationInfoEntity::tableName(), $data, $map)
                                       ->execute();
                }
            }

            if(! empty($list['priceResult'])){
                foreach ($list['priceResult'] as $value){
                    $data = [
                        'price'         => $value['price'],
                        'unit'          => $value['unit'],
                        'modified_on'   => $value['modified_on'],
                        'modified_by'   => $value['modified_by'],
                    ];

                    $map = [
                        'application_id' => $value['application_id'],
                    ];

                    Yii::info('商机系统产品主数据，价格更新参数：' . json_encode($data));

                    $db->createCommand()->update(ApplicationPriceEntity::tableName(), $data, $map)
                                        ->execute();
                }
            }

            Yii::info('商机系统产品主数据更新成功');

            $result = true;
            $transaction->commit();

        } catch (\Exception $e){
            Yii::info('商机系统产品主数据更新失败，原因：' . $e->getMessage());

            $result = false;
            $transaction->rollBack();
        }

        return $result;
    }

}